package com.dragon.mmochat.model.serverListDao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;

import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;

import com.dragon.mmochat.dao.MmochatRoleDao;
import com.dragon.mmochat.model.enumType.MmochatBigMoneyCostType;
import com.dragon.mmochat.model.enumType.MmochatChatChannelType;
import com.dragon.mmochat.model.enumType.MmochatFamilyType;
import com.dragon.mmochat.model.enumType.MmochatGangSkillType;
import com.dragon.mmochat.model.enumType.MmochatOtherSystemSettingType;
import com.dragon.mmochat.model.enumType.MmochatPropType;
import com.dragon.mmochat.model.enumType.MmochatRoleType;
import com.dragon.mmochat.model.enumType.MmochatSecondRoleType;
import com.dragon.mmochat.model.enumType.MmochatShowRoleSet;
import com.dragon.mmochat.model.enumType.MmochatSkillType;
import com.dragon.mmochat.model.enumType.MmochatSpecialSkillType;
import com.dragon.mmochat.model.enumType.MmochatStorePwdState;
import com.dragon.mmochat.model.gang.MmochatGangSkill;
import com.dragon.mmochat.model.object.MmochatPackageGrid;
import com.dragon.mmochat.model.object.MmochatPropEffect;
import com.dragon.mmochat.model.role.MmochatFriend;
import com.dragon.mmochat.model.role.MmochatPet;
import com.dragon.mmochat.model.role.MmochatPlayer;
import com.dragon.mmochat.model.role.MmochatSimplePlayer;
import com.dragon.mmochat.model.serverListStatistics.MmochatPayRecord;
import com.dragon.mmochat.model.skill.MmochatSkill;
import com.dragon.mmochat.model.skill.MmochatSpecialSkill;
import com.dragon.mmochat.model.statistics.MmochatMixStatistics;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class Dao_subServer extends SimpleJdbcDaoSupport {
	private static final SimpleRoleRowMapper rowMap = new SimpleRoleRowMapper();
	private static final SimpleDirectPayRowMapper directPayRowMap = new SimpleDirectPayRowMapper();
	private static final SimpleKBPayRowMapper kBPayRowMap = new SimpleKBPayRowMapper();
	private static final DayLogRowMapper dayLogRowMapper = new DayLogRowMapper();
	private static final RoleRowMapper roleMapper = new RoleRowMapper();
	private static final ChenHaoRowMapper chenHaoMapper = new ChenHaoRowMapper();

	// 获取指定时间内注册的skyId列表
	private static final String getSkyIdByDateSql = "select skyid from role where create_time >= ? and create_time < ?";

	public List<Long> getSkyIdByDate(Timestamp start, Timestamp end) {
		return getSimpleJdbcTemplate().query(getSkyIdByDateSql, rowMap, start,
				end);
	}

	// 获取指定时间内的充值卡充值记录
	private static final String getDirectPayRecordSql = "select skyid, rmb from direct_pay_orders "
			+ "where create_time >= ? and create_time < ? and result = 1";

	public List<MmochatPayRecord> getDirectPayRecord(long start, long end) {
		return getSimpleJdbcTemplate().query(getDirectPayRecordSql,
				directPayRowMap, start, end);
	}

	// 获取指定时间内的K币充值记录
	private static final String getKBPayRecordSql = "select skyid, kb from kb_pay_orders "
			+ "where create_time >= ? and create_time < ?";

	public List<MmochatPayRecord> getKBPayRecord(long start, long end) {
		return getSimpleJdbcTemplate().query(getKBPayRecordSql, kBPayRowMap,
				start, end);
	}

	// 查询指定时间内的每日记录
	private static final String getDayLogByTimeSql = "select "
			+ "date,main_point_to_cost_bigmoney,prop_use_map,"
			+ "total_bigmoney_rest,total_smallmoney_rest,online_top,"
			+ "online_map,login_num,online_time_average,"
			+ "bigmoney_pay_total_money "
			+ " from day_log where date >= ? and date < ? order by date desc";

	public List<MmochatMixStatistics> getDayLogByTime(Timestamp startDate,
			Timestamp endDate) {
		return getSimpleJdbcTemplate().query(getDayLogByTimeSql,
				dayLogRowMapper, startDate, endDate);
	}

	// 获取跨服区使用的角色信息
	private static final String getRoleSql = "select id,delete,skyid,name,level,exp,"
			+ "sexual,map,line,x,y,type,cur_blood,cur_sprit,blood_point,"
			+ "attack_point,sprit_point,speed_point,space_point,small_money,"
			+ "big_money,family,dao,zhanji,show_role_set_value,accept_friendlypk,"
			+ "accept_zhanjipk,friendlist_bmp,accept_stranger_message,check_addmefriend,"
			+ "accept_addmefriend,teacher_name,teacher_score,screen_role_num,"
			+ "attack_gift_point,sprit_gift_point,blood_gift_point,defend_gift_point,"
			+ "speed_gift_point,space_gift_point,wife_name,life_turn,second_role_type,"
			+ "lock_time_point,store_pwd,store_pwd_state,release_store_pwd_time,skills,"
			+ "pets,friends,enermys,prop_effects,show_chat_set,gang_skills,students,"
			+ "package,other_system_setting,special_skills,myfans,pk_score from role where id = ?";

	public MmochatPlayer getRole(int roleId) {
		try {
			return getSimpleJdbcTemplate().queryForObject(getRoleSql,
					roleMapper, roleId);
		} catch (EmptyResultDataAccessException e) {
			return null;
		}
	}

	// 更新竞技点
	private static final String updatePkScoreSql = "update role set pk_score = ? where id = ?";

	public void updatePkScore(int pkScore, int roleId) {
		getSimpleJdbcTemplate().update(updatePkScoreSql, pkScore, roleId);
	}

	// 获取称号
	private static final String getChenHaoSql = "select chenhao from role where id = ?";

	public String getChenHao(int roleId) {
		return getSimpleJdbcTemplate().queryForObject(getChenHaoSql,
				chenHaoMapper, roleId);
	}

	// 更新竞技点和称号
	private static final String updatePkScoreAndChenHaoSql = "update role set pk_score = ?, chenhao = ? where id = ?";

	public void updatePkScoreAndChenHao(int pkScore, String chenHao, int roleId) {
		getSimpleJdbcTemplate().update(updatePkScoreAndChenHaoSql, pkScore,
				chenHao, roleId);
	}

	// ////////////////////////////////

	static class SimpleRoleRowMapper implements ParameterizedRowMapper<Long> {
		@Override
		public Long mapRow(ResultSet rs, int rowNum) throws SQLException {
			return rs.getLong("skyid");
		}
	}

	static class SimpleDirectPayRowMapper implements
			ParameterizedRowMapper<MmochatPayRecord> {
		@Override
		public MmochatPayRecord mapRow(ResultSet rs, int rowNum)
				throws SQLException {
			MmochatPayRecord r = new MmochatPayRecord();
			r.setRmb(rs.getInt("rmb"));
			r.setSkyId(rs.getLong("skyid"));
			return r;
		}
	}

	static class SimpleKBPayRowMapper implements
			ParameterizedRowMapper<MmochatPayRecord> {
		@Override
		public MmochatPayRecord mapRow(ResultSet rs, int rowNum)
				throws SQLException {
			MmochatPayRecord r = new MmochatPayRecord();
			r.setRmb(rs.getInt("kb"));
			r.setSkyId(rs.getLong("skyid"));
			return r;
		}
	}

	static class DayLogRowMapper implements
			ParameterizedRowMapper<MmochatMixStatistics> {
		@Override
		public MmochatMixStatistics mapRow(ResultSet rs, int rowNum)
				throws SQLException {
			MmochatMixStatistics data = new MmochatMixStatistics();
			data.setStamp(rs.getTimestamp("date"));

			Gson gson = new Gson();
			String str = rs.getString("main_point_to_cost_bigmoney");
			if (str != null) {
				Map<MmochatBigMoneyCostType, Long> map = gson.fromJson(str,
						new TypeToken<Map<MmochatBigMoneyCostType, Long>>() {
						}.getType());
				if (map != null) {
					data.setMain_point_to_cost_bigmoney(map);
				}
			}
			str = rs.getString("prop_use_map");
			if (str != null) {
				Map<MmochatPropType, Long> map = gson.fromJson(str,
						new TypeToken<Map<MmochatPropType, Long>>() {
						}.getType());
				if (map != null) {
					data.setTodayPropCostPointMap(map);
				}
			}
			data.setTotal_bigmoney_rest(rs.getLong("total_bigmoney_rest"));
			data.setTotal_smallmoney_rest(rs.getLong("total_smallmoney_rest"));
			data.setOnline_top(rs.getInt("online_top"));
			str = rs.getString("online_map");
			if (str != null) {
				Map<Long, Integer> onlineMap = gson.fromJson(str,
						new TypeToken<Map<Long, Integer>>() {
						}.getType());
				if (onlineMap != null) {
					data.setOnlineMap(onlineMap);
				}
			}
			data.setLogin_num(rs.getInt("login_num"));
			data.setOnline_time_average(rs.getInt("online_time_average"));
			data.setBigmoney_pay_total_money(rs
					.getInt("bigmoney_pay_total_money"));
			return data;
		}
	}

	static class RoleRowMapper implements ParameterizedRowMapper<MmochatPlayer> {
		@Override
		public MmochatPlayer mapRow(ResultSet rs, int rowNum)
				throws SQLException {
			MmochatPlayer role = new MmochatPlayer();
			role.setRoleId(rs.getInt("id"));
			role.setDeleted(rs.getBoolean("delete"));
			role.setSkyId(rs.getLong("skyid"));
			role.setName(rs.getString("name"));
			role.setLevel(rs.getInt("level"));
			role.setExp(rs.getInt("exp"));
			role.setSexual(rs.getInt("sexual"));
			role.setMapId(rs.getInt("map"));
			role.setLine(rs.getInt("line"));
			role.setX(rs.getInt("x"));
			role.setY(rs.getInt("y"));
			role.setRoleType(MmochatRoleType.get(rs.getInt("type")));
			role.setCurBlood(rs.getInt("cur_blood"));
			role.setCurSprit(rs.getInt("cur_sprit"));
			role.setBlood_point(rs.getInt("blood_point"));
			role.setAttack_point(rs.getInt("attack_point"));
			role.setSprit_point(rs.getInt("sprit_point"));
			role.setSpeed_point(rs.getInt("speed_point"));
			role.setSpace_point(rs.getInt("space_point"));
			role.setSmall_money(rs.getInt("small_money"));
			role.setBig_money(rs.getInt("big_money"));
			role.setFamily(MmochatFamilyType.get(rs.getInt("family")));
			role.setDao(rs.getInt("dao"));
			role.setZhanji(rs.getInt("zhanji"));

			Integer show_role_set_value = rs.getInt("show_role_set_value");
			if (show_role_set_value != null) {
				MmochatShowRoleSet set = MmochatShowRoleSet
						.get(show_role_set_value);
				if (set != null) {
					role.setShowRoleSet(set);
				}
			}

			role.setAcceptFriendlyPk(rs.getBoolean("accept_friendlypk"));
			role.setAcceptZhanjiPk(rs.getBoolean("accept_zhanjipk"));

			role.setBmpId(rs.getInt("friendlist_bmp"));
			role.setAcceptStrangerMessage(rs
					.getBoolean("accept_stranger_message"));
			role.setCheckAddMeFriend(rs.getBoolean("check_addmefriend"));
			role.setAcceptAddMeFriend(rs.getBoolean("accept_addmefriend"));
			role.setTeacher_name(rs.getString("teacher_name"));
			role.setTeacherScore(rs.getInt("teacher_score"));
			role.setMax_screen_role_num(rs.getInt("screen_role_num"));
			role.setAttack_gift_point(rs.getInt("attack_gift_point"));
			role.setSprit_gift_point(rs.getInt("sprit_gift_point"));
			role.setBlood_gift_point(rs.getInt("blood_gift_point"));
			role.setDefend_gift_point(rs.getInt("defend_gift_point"));
			role.setSpeed_gift_point(rs.getInt("speed_gift_point"));
			role.setSpace_gift_point(rs.getInt("space_gift_point"));
			String wifeName = rs.getString("wife_name");
			if (wifeName != null && wifeName.length() > 0) {
				role.setWife_name(wifeName);
			}
			Integer lifeTurn = rs.getInt("life_turn");
			if (lifeTurn != null) {
				role.setLife_turn(lifeTurn);
			}

			Integer second_role_type = rs.getInt("second_role_type");
			if (second_role_type != null) {
				role.setSecond_role_type(MmochatSecondRoleType
						.get(second_role_type));
			}

			Long lock_time_point = rs.getLong("lock_time_point");
			if (lock_time_point != null) {
				role.setLock_time_point(lock_time_point);
			}

			String pwd = rs.getString("store_pwd");
			if (pwd != null) {
				role.setStore_pwd(pwd);
			}

			Integer store_pwd_state = rs.getInt("store_pwd_state");
			if (store_pwd_state != null) {
				MmochatStorePwdState state = MmochatStorePwdState
						.get(store_pwd_state);
				if (state != null) {
					role.setStore_pwd_state(state);
				}
			}

			Long release_store_pwd_time = rs.getLong("release_store_pwd_time");
			if (release_store_pwd_time != null) {
				role.setReleaseStorePwdTime(release_store_pwd_time);
			}

			Integer pk_score = rs.getInt("pk_score");
			if (pk_score != null) {
				role.setPk_score(pk_score);
			}

			// TODO:GSON开始
			Gson gson = new Gson();

			String str;

			str = rs.getString("skills");
			if (str != null) {
				Map<MmochatSkillType, MmochatSkill> skills = gson.fromJson(str,
						new TypeToken<Map<MmochatSkillType, MmochatSkill>>() {
						}.getType());
				if (skills != null) {
					role.setSkills(skills);
				}
			}
			str = rs.getString("pets");
			if (str != null) {
				Map<Integer, MmochatPet> pets = gson.fromJson(str,
						new TypeToken<Map<Integer, MmochatPet>>() {
						}.getType());
				if (pets != null) {
					role.setPets(pets);
				}
			}
			str = rs.getString("friends");
			if (str != null) {
				Map<Integer, MmochatFriend> friends = gson.fromJson(str,
						new TypeToken<Map<Integer, MmochatFriend>>() {
						}.getType());
				if (friends != null) {
					role.setMyDearFriends(friends);
				}
			}
			str = rs.getString("enermys");
			if (str != null) {
				Map<Integer, MmochatFriend> enermys = gson.fromJson(str,
						new TypeToken<Map<Integer, MmochatFriend>>() {
						}.getType());
				if (enermys != null) {
					role.setMyEnermys(enermys);
				}
			}

			str = rs.getString("prop_effects");
			if (str != null) {
				Map<Integer, MmochatPropEffect> prop_effects = gson.fromJson(
						str, new TypeToken<Map<Integer, MmochatPropEffect>>() {
						}.getType());
				if (prop_effects != null) {
					role.setPropEffects(prop_effects);
				}
			}

			str = rs.getString("show_chat_set");
			if (str != null) {
				Map<MmochatChatChannelType, Boolean> show_chat_set = gson
						.fromJson(
								str,
								new TypeToken<Map<MmochatChatChannelType, Boolean>>() {
								}.getType());
				if (show_chat_set != null) {
					role.setShowChatSet(show_chat_set);
				}
			}

			str = rs.getString("gang_skills");
			if (str != null) {
				Map<MmochatGangSkillType, MmochatGangSkill> gangSkills = gson
						.fromJson(
								str,
								new TypeToken<Map<MmochatGangSkillType, MmochatGangSkill>>() {
								}.getType());
				if (gangSkills != null) {
					role.setGangSkills(gangSkills);
				}
			}

			str = rs.getString("students");
			if (str != null) {
				Map<Integer, String> students = gson.fromJson(str,
						new TypeToken<Map<Integer, String>>() {
						}.getType());
				if (students != null) {
					role.setStudents(students);
				}
			}

			str = rs.getString("package");
			if (str != null) {
				Map<Integer, MmochatPackageGrid> myPackage = gson.fromJson(str,
						new TypeToken<Map<Integer, MmochatPackageGrid>>() {
						}.getType());
				if (myPackage != null) {
					role.setMyPackage(myPackage);
				}
			}

			str = rs.getString("other_system_setting");
			if (str != null) {
				Map<MmochatOtherSystemSettingType, Boolean> otherSystemSetting = gson
						.fromJson(
								str,
								new TypeToken<Map<MmochatOtherSystemSettingType, Boolean>>() {
								}.getType());
				if (otherSystemSetting != null) {
					role.setOtherSystemSetting(otherSystemSetting);
				}
			}

			str = rs.getString("special_skills");
			if (str != null) {
				Map<MmochatSpecialSkillType, MmochatSpecialSkill> specialSkills = gson
						.fromJson(
								str,
								new TypeToken<Map<MmochatSpecialSkillType, MmochatSpecialSkill>>() {
								}.getType());
				if (specialSkills != null) {
					role.setSpecialSkills(specialSkills);
				}
			}

			str = rs.getString("myfans");
			if (str != null) {
				Map<Integer, Integer> myfans = gson.fromJson(str,
						new TypeToken<Map<Integer, Integer>>() {
						}.getType());
				if (myfans != null) {
					role.setMyFans(myfans);
				}
			}

			return role;

		}
	}

	static class ChenHaoRowMapper implements ParameterizedRowMapper<String> {
		@Override
		public String mapRow(ResultSet rs, int rowNum) throws SQLException {
			return rs.getString("chenhao");
		}
	}
}
